import SwiftUI

struct HomeView: View {
    @StateObject private var viewModel: HomeViewModel

    init(service: DestinationService) {
        _viewModel = StateObject(wrappedValue: HomeViewModel(destinationService: service))
    }

    var body: some View {
        NavigationStack {
            content
            .navigationTitle("探索")
        }
        .task { await viewModel.load() }
    }

    @ViewBuilder
    private var content: some View {
        if viewModel.isLoading {
            ProgressView("加载中...")
        } else if let message = viewModel.errorMessage {
            ContentUnavailableView("加载失败", systemImage: "exclamationmark.triangle", description: Text(message))
        } else if viewModel.popularDestinations.isEmpty {
            ContentUnavailableView("暂无目的地", systemImage: "airplane")
        } else {
            List(viewModel.popularDestinations) { destination in
                DestinationRow(destination: destination)
            }
            .listStyle(.insetGrouped)
        }
    }
}

#Preview {
    let env = AppEnvironment()
    HomeView(service: env.destinationService)
        .environmentObject(env)
}


